import {
  Controller,
  Post,
  Get,
  Body,
  Param,
  Headers,
  HttpCode,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiExcludeEndpoint } from '@nestjs/swagger';
import { PaymentService } from './payment.service';
import { Public } from '../auth/decorators/public.decorator';

@ApiTags('支付')
@Controller('payment')
export class PaymentController {
  constructor(private readonly paymentService: PaymentService) {}

  /**
   * 支付宝支付回调
   */
  @Post('alipay/notify')
  @Public()
  @HttpCode(200)
  @ApiExcludeEndpoint() // 不在Swagger中显示
  async alipayNotify(@Body() body: any) {
    try {
      const success = await this.paymentService.handleAlipayNotify(body);
      if (success) {
        return 'success'; // 支付宝要求返回 success 字符串
      }
      return 'fail';
    } catch (error) {
      console.error('支付宝回调处理失败:', error);
      return 'fail';
    }
  }

  /**
   * 微信支付回调
   */
  @Post('wechat/notify')
  @Public()
  @HttpCode(200)
  @ApiExcludeEndpoint() // 不在Swagger中显示
  async wechatNotify(@Headers() headers: any, @Body() body: any) {
    try {
      const success = await this.paymentService.handleWechatNotify({
        headers,
        body,
        resource: body.resource,
      });

      if (success) {
        return { code: 'SUCCESS', message: '成功' };
      }
      return { code: 'FAIL', message: '失败' };
    } catch (error) {
      console.error('微信支付回调处理失败:', error);
      return { code: 'FAIL', message: error.message };
    }
  }

  /**
   * 查询支付状态
   */
  @Get(':paymentNo/status')
  @Public()
  @ApiOperation({ summary: '查询支付状态' })
  async queryStatus(@Param('paymentNo') paymentNo: string) {
    const payment = await this.paymentService.queryPaymentStatus(paymentNo);
    return {
      code: 200,
      message: '查询成功',
      data: {
        status: payment.status,
        paidAt: payment.paidAt,
        amount: payment.amount,
      },
    };
  }
}
